<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ucenter extends CI_Controller {
	
	private $user_id;
	private $pageSize = 20;
	
	public function __construct()
	{
		parent::__construct();
		$this->user_id = $this->session->userdata('user_id');
		if(!$this->user_id)
		{
			header("location:".base_url("login"));
			exit;
		} 
	}
	
	/**
	 * 用户订单列表
	 * 
	 * Enter description here ...
	 */
	public function index()
	{			
		$this->load->model('m_order');
		$page = $this->input->get('page');
		
		//商品的数量
		$page = $page ? $page : '1';
		$total_order = $this->m_order->selectUserOrderAmount($this->user_id);
		$total_order = $total_order['0']->orderAmount?$total_order['0']->orderAmount:'0';
		$pagination = array(
				'pageSize'=>$this->pageSize,
				'totalRows'=>$total_order,
				'currentPage'=>$page,
				'baseUrl'=>base_url().'ucenter/index'
		);
		$this->load->library('pagination',$pagination);
		
		$user_order = $this->m_order->selectUserOrderById($this->user_id, ($page -1)*$this->pageSize,$this->pageSize);
		
		$data = array('style'=>array('ucenter/sidebar','ucenter/index'));
		$data['user_order'] = $user_order;
		
		$this->load->view('header',$data);
		$this->load->view('ucenter/index');
		$this->load->view('footer');
	}
	
	/**
	 * 用户逻辑删除订单
	 * 
	 * Enter description here ...
	 */
	public function hideOrder()
	{
		$order_id = $this->input->post("id");
		$this->load->model("m_order");
		if($this->m_order->hideOrder($order_id))
		{
			echo '{"status":"10000","order_id":"'.$order_id.'"}';
		}
	}
	
	/**
	 * 用户取消订单
	 * Enter description here ...
	 */
	public function cancelOrder()
	{
		$order_id = $this->input->post("id");
		$this->load->model("m_order");
		
		$order_info = $this->m_order->selectOrderById($order_id);
		
		//如果用户订单状态大于10,即已经处于配送中了,则不可以取消订单
		if( ($order_info['0']->order_status > 20))
		{
			echo '{"status":"10007","order_id":"'.$order_info['0']->status.'"}';
			exit;
		}
		if($this->m_order->changeUserOrderStatus('60',$order_id))
		{
			echo '{"status":"10000"}';
		}
	}
	
	/*public function address()
	{
		$this->load->model("m_user");
		$address = $this->m_user->selectUserAddress();
		
		$data = array('style'=>array('ucenter/sidebar','ucenter/index'),'address'=>$address);
		$this->load->view('header',$data);
		$this->load->view('ucenter/address');
		$this->load->view('footer');
	}*/
	
	/**
	 * 新增加地址
	 */
	/*public function addAdress()
	{
		$user_name = $this->input->post('user_name');
		$user_phone = $this->input->post('user_phone');
		$user_address = $this->input->post('user_address');
		
		$this->load->model("m_user");
		if($this->m_user->addUserAddress($user_name,$user_phone,$user_address))
		{
			echo '{"status":"10000"}';
		}
		
		
	}*/
	
	/**
	 * 修改头像
	 */
	public function headimg()
	{
		$data = array('style'=>array('ucenter/sidebar','ucenter/headimg'));
		$this->load->model("m_user");
		$user_info = $this->m_user->selectUserById($this->user_id);
		$data['user_info']=$user_info;
		
		$this->load->view('header',$data);
		$this->load->view('ucenter/headimg');
		$this->load->view('footer');
	}
	
	public function uploadHeadimg()
	{

		if (!$_FILES['Filedata']) 
		{
			die ( 'Image data not detected!' );
		}
		if ($_FILES['Filedata']['error'] > 0) 
		{
			switch ($_FILES ['Filedata'] ['error']) 
			{
				case 1 :
					$error_log = 'The file is bigger than this PHP installation allows';
					break;
				case 2 :
					$error_log = 'The file is bigger than this form allows';
					break;
				case 3 :
					$error_log = 'Only part of the file was uploaded';
					break;
				case 4 :
					$error_log = 'No file was uploaded';
					break;
				default :
					break;
			}
			die ( 'upload error:' . $error_log );
		} 
		else 
		{
			$img_data = $_FILES['Filedata']['tmp_name'];
			$size = getimagesize($img_data);
			$file_type = $size['mime'];
			if (!in_array($file_type, array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))) 
			{
				$error_log = 'only allow jpg,png,gif';
				die ( 'upload error:' . $error_log );
			}
			switch($file_type) 
			{
				case 'image/jpg' :
				case 'image/jpeg' :
				case 'image/pjpeg' :
					$extension = 'jpg';
					break;
				case 'image/png' :
					$extension = 'png';
					break;
				case 'image/gif' :
					$extension = 'gif';
					break;
			}	
		}
		if (!is_file($img_data)) 
		{
			die ( 'Image upload error!' );
		}
		//图片保存路径,默认保存在该代码所在目录(可根据实际需求修改保存路径)
		$base_furl = './uploads/headimg/';
		$base_path = $base_furl.'region/'; //原图
		$base_thumb_path_40 = $base_furl.'thumb_40/'; //40_40缩略图路径
	
		$data_path = date("Y").'/'.date("m")."/".date("d")."/";
	
		$upload_path = $base_path.$data_path;
		$upload_thumb_path_40 = $base_thumb_path_40.$data_path;
	
		//图片保存路径,默认保存在该代码所在目录(可根据实际需求修改保存路径)
		if(!file_exists($upload_path))
		{
			mkdir($upload_path,0777,TRUE);
		}
	
		//缩略50图片保存路径
		if(!file_exists($upload_thumb_path_40))
		{
			mkdir($upload_thumb_path_40,0777,TRUE);
		}
		
		//$save_path = dirname( __FILE__ );
		$uinqid = uniqid();
		$filename = $upload_path  . $uinqid . '.' . $extension;
		
		
		$result = move_uploaded_file( $img_data, $filename );
		if ( ! $result || ! is_file( $filename ) ) 
		{
			die ( 'Image upload error!' );
		}
		
		$this->create_thumb($filename,$upload_thumb_path_40.$uinqid.'.'.$extension,40);
		
		$this->load->model("m_user");
		if($this->m_user->updateUserHeadimg($data_path.$uinqid.'.'.$extension))
		{
			echo substr($filename, 2);
		}
	}
	
	/**
	 * 创建缩略图
	 */
	public function create_thumb($sourec_image,$new_image,$size)
	{
		$config['image_library'] = 'gd2';
		$config['source_image'] = $sourec_image;
		$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['new_image'] = $new_image;
		$config['thumb_marker']='';
		$config['width'] = $size;
		$config['height'] = $size;
			
		$this->load->library('image_lib', $config);
		$this->image_lib->initialize($config);
		if($this->image_lib->resize())
		{
			$this->image_lib->clear();
			return $new_image;
		}
	
	}
	
	/**
	 * 用户书签
	 */
	public function collect()
	{
		$this->load->model('m_bookmark');
		$page = $this->input->get('page');
		//商品的数量
		$page = $page ? $page : '1';
		$total_bookmark = $this->m_bookmark->selectuserBookmarkAmount($this->user_id);
		$total_bookmark = $total_bookmark['0']->bookmarkAmount?$total_bookmark['0']->bookmarkAmount:'0';
		$pagination = array(
				'pageSize'=>$this->pageSize,
				'totalRows'=>$total_bookmark,
				'currentPage'=>$page,
				'baseUrl'=>base_url().'ucenter/collect'
		);
		$this->load->library('pagination',$pagination);
		$user_bookmark = $this->m_bookmark->selectUserBookmark($this->user_id, ($page-1)*$this->pageSize,$this->pageSize);
		
		$data = array('style'=>array('ucenter/sidebar','ucenter/collect'),'user_bookmark'=>$user_bookmark);
		$this->load->view('header',$data);
		$this->load->view('ucenter/collect');
		$this->load->view('footer');
	}
	
	/**
	 * 删除书签
	 * Enter description here ...
	 */
	public function deleteBookmark()
	{
		$mark_id = $this->input->post("mark_id");
		$book_id = $this->input->post("book_id");
		$this->load->model("m_bookmark");
		if($this->m_bookmark->deleteUserBookmark($mark_id))
		{
			$bookmark_amount = $this->m_bookmark->selectuserBookmarkAmount($this->user_id);
			$this->m_bookmark->bookmarkLog($book_id,$this->user_id,'2');
			echo '{"status":"10000","mark_id":"'.$mark_id.'","mark_amount":"'.$bookmark_amount['0']->bookmarkAmount.'"}';
		}
		
	}
	
	/**
	 * 用户设置
	 * Enter description here ...
	 */
	public function setting()
	{
		$this->load->model("m_user");
		$user = $this->m_user->selectUserById($this->user_id);
		
		$data = array('style'=>array('ucenter/sidebar','ucenter/setting'),'user'=>$user);
		$this->load->view('header',$data);
		$this->load->view('ucenter/setting');
		$this->load->view('footer');
		
		
	}
	
	public function SettingAct()
	{
		$user_nickname = $this->input->post('nickname');
		$this->load->model("m_user");
		
		if(!$user_nickname)
		{
			echo '{"status":"10008"}';
			exit;
		}
		
		$this->load->library('form_validation');
		
		//验证昵称是否正确
		$this->form_validation->set_rules('nickname', 'nickname', 'required|max_length[10]');
		if ($this->form_validation->run() == FALSE)
		{
			echo '{"status":"10010"}';
			exit;
		}
		
		//验证昵称格式
		if(!preg_match("/^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_]{1,}$/u", $user_nickname))
		{
			echo '{"status":"10010"}';
			exit;
		}
		
		//验证昵称是否重复
		$user_base_info = $this->m_user->selectUserById($this->user_id);
		if( $user_base_info['0']->user_nickname != $user_nickname)
		{
			if($this->m_user->selectUserByNickname($user_nickname))
			{
				echo '{"status":"10009"}';
				exit;
			}
		}
		if($this->m_user->updateUserBaseInfo($this->user_id, $user_nickname ))
		{
			$this->session->set_userdata('user_nickname',$user_nickname );
			echo '{"status":"10000"}';
			
		}

	}
	
	/**
	 * 修改密码
	 * @param unknown $email
	 */
	public function password()
	{
		$this->load->model("m_user");
		$user = $this->m_user->selectUserMoreByID($this->user_id);
	
		$data = array('style'=>array('ucenter/sidebar','ucenter/setting'),'user'=>$user);
		$this->load->view('header',$data);
		$this->load->view('ucenter/password');
		$this->load->view('footer');
	}
	
	/**
	 * 保存修改的密码
	 */
	public function savePassword()
	{
		$password = $this->input->post();
		
		if( (strlen($password['old_password']) >16)  || (strlen($password['old_password']) < 6) )
		{
			echo '{"status":"10611"}';//原密码位数不正确
			exit;
		}
		if((strlen($password['new_password']) >16)  || (strlen($password['new_password']) < 6))
		{
			echo '{"status":"10612"}';//新密码位数不正确
			exit;
		}
		if((strlen($password['again_password']) >16)  || (strlen($password['again_password']) < 6))
		{
			echo '{"status":"10613"}';//确认密码位数不正确
			exit;
		}
		if( $password['new_password'] != $password['again_password'] )
		{
			echo '{"status":"10614"}';//两次输入密码不一致
			exit;
		}
		$this->load->model("m_user");
		
		$user_info = $this->m_user->selectUserMoreByID($this->user_id);
		
		$db_password = $user_info['0']->user_password;
		$db_validcode = $user_info['0']->validcode;

		if($db_password != sha1(md5($password['old_password']).$db_validcode))
		{
			echo '{"status":"10615"}'; // 初始密码不正确
			exit;
		}

		//用于产生随机字符串
		$this->load->helper('string');
		//产生16位随机字符串
		$validCode = random_string('alnum', 16);
		
		$user_password = sha1(md5($password['new_password']).$validCode);
		
		$data = array("user_password"=>$user_password,"validcode"=>$validCode);

		if($this->m_user->updateUserBaseInfo($this->user_id,$data))
		{
			echo '{"status":"10000"}';
		}
	}
	
	public function sendEmail($email)
	{
		$this->load->library('email');
		$config['protocol'] = 'smtp';
		$config['smtp_host'] = 'smtp.163.com';
		$config['smtp_user'] = 'yanyinghq@163.com';
		$config['smtp_pass'] = 'gx1992x03y23hq';
		$this->email->initialize($config);
		$this->email->from('yanyinghq@163.com', 'Your Name');
		$this->email->to($email);
		$this->email->subject('Email Test');
		$this->email->message('Testing the email class.');
		$this->email->send();
	}
}

/* End of file Register.php */
/* Location: ./application/controllers/Register.php */